#include <Windows.h>
#include <iostream>
#include "DB.h"

using namespace std;

namespace app {

  DB::DB() : db_(nullptr) {}
  DB::~DB() { close(); }

  namespace {
    void trace_callback(void*, const char* msg) {
      wchar_t wmsg[512];
      MultiByteToWideChar(CP_UTF8, 0, msg, -1, wmsg, 512);
      wcout << wmsg << endl;
    }
  }
  bool DB::open(const char* path) {
    int ret = sqlite3_open(path, &db_);
#ifdef DEBUG
    if ( ret == SQLITE_OK ) {
      sqlite3_trace(db_, &trace_callback,nullptr);
    }
#endif
    return ret == SQLITE_OK;
  }

  void DB::close() {
    if ( db_ != nullptr ) {
      sqlite3_close(db_);
    }
  }

  int DB::exec(const wchar_t* sql, callback cb, void* arg) {
    return sqlite3_exec16_ex(db_, sql, cb, arg);
  }

  int DB::exec(const wstring& sql, callback cb, void* arg) {
    return sqlite3_exec16_ex(db_, sql.c_str(), cb, arg);
  }

  DB& DB::instance() {
    static DB instance_;
    return instance_;
  }

  bad_book::bad_book(const std::wstring& id) : std::domain_error("no such book"), id_(id) {}
  wstring bad_book::id() const { return id_; }

  bad_customer::bad_customer(const std::wstring& id) : std::domain_error("no such customer"), id_(id) {}
  wstring bad_customer::id() const { return id_; }

}

